package com.irate.fragment;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.Header;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.InputType;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.TextView;
import android.widget.Toast;

import com.ipaulpro.afilechooser.utils.FileUtils;
import com.irate.activity.ListCategoryActivity;
import com.irate.activity.ListCriteriaActivity;
import com.irate.activity.R;
import com.irate.dao.RatingCategoryDAO;
import com.irate.http.AsyncHttpResponseHandler;
import com.irate.model.RatingCategory;
import com.irate.model.RatingDetailType;
import com.irate.provider.ContentManager;

public class RatingFragment extends Fragment {
	protected ImageView search_back_button;
	protected TextView title;
	protected TextView rating_submit_rating;
	protected ImageView content_category_expand_button;
	protected ImageView content_criteria_expand_button;
	protected View mainView;
	protected TextView content_category_rank;
	protected List<RatingCategory> listCategory;
	protected LinearLayout ratingCategoryDetailContent;
	protected RatingCategoryDAO ratingCategoryDao;
	protected ProgressDialog dialog;

	protected ImageView rating_add_photo;
	protected ImageView rating_add_comment;
	protected ImageView rating_privacy;

	protected View contentAddPhoto;
	protected View contentAddComment;
	protected View contentPrivacy;

	protected int privacy = 0;
	protected int temp = 0;

	private static final int REQUEST_CODE = 6385;
	protected String picture_path;

	protected TextView upload_file_name;

	protected PopupWindow pw_photo;
	protected List<EditText> listEditText;
	protected CheckBox share_on_facebook;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		mainView = inflater.inflate(R.layout.rating_layout, null);
		return mainView;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

		init();
		execute();

	}

	@Override
	public void onResume() {
		super.onResume();

		if (ContentManager.getInstance().getRating_category() != null) {
			if (!content_category_rank
					.getText()
					.toString()
					.equals(ContentManager.getInstance().getRating_category()
							.getCategory_name())) {

				content_category_rank.setText(ContentManager.getInstance()
						.getRating_category().getCategory_name());
				if (ContentManager.getInstance().getListRatingCategory().size() > ContentManager
						.getInstance().getCategory_index_selected())
					initCategoryView(ContentManager.getInstance()
							.getCategory_index_selected());
			}
		}

	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case REQUEST_CODE:
			// If the file selection was successful
			if (resultCode == getActivity().RESULT_OK) {
				if (data != null) {
					// Get the URI of the selected file
					final Uri uri = data.getData();
					try {
						// Get the file path from the URI
						final String path = FileUtils.getPath(getActivity(),
								uri);

						if (path != null) {
							picture_path = path;
						} else {
							picture_path = getBitmap("picture.jpg", uri);
						}

						if (upload_file_name != null) {
							upload_file_name.setText(new File(picture_path)
									.getName());
						}

						File fileContent = new File(picture_path);
						if (fileContent.length() / 1024 < 2000) {
							dialog = ProgressDialog.show(getActivity(),
									getResources().getString(R.string.upload),
									getResources().getString(R.string.loading),
									true);

							ratingCategoryDao.upLoadPhoto(picture_path,
									pw_photo, getActivity(), dialog);
						} else {

							if (dialog != null)
								dialog.dismiss();

							Toast.makeText(getActivity(), "File is too large!",
									Toast.LENGTH_SHORT).show();
						}

					} catch (Exception e) {
						Log.e("FileSelectorTestActivity", "File select error",
								e);
					}
				}
			}
			break;
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	private void init() {
		listCategory = new ArrayList<RatingCategory>();

		search_back_button = (ImageView) getActivity().findViewById(
				R.id.search_button);
		title = (TextView) getActivity().findViewById(R.id.site_title);
		rating_submit_rating = (TextView) getActivity().findViewById(
				R.id.rating_submit_rating);
		content_category_expand_button = (ImageView) getActivity()
				.findViewById(R.id.content_category_expand_button);

		content_criteria_expand_button = (ImageView) getActivity()
				.findViewById(R.id.content_criteria_expand_button);

		content_category_rank = (TextView) getActivity().findViewById(
				R.id.content_category_rank);

		ratingCategoryDetailContent = (LinearLayout) getActivity()
				.findViewById(R.id.ratingCategoryDetailContent);

		ratingCategoryDao = new RatingCategoryDAO();

		rating_add_photo = (ImageView) getActivity().findViewById(
				R.id.rating_add_photo);
		rating_add_comment = (ImageView) getActivity().findViewById(
				R.id.rating_add_comment);
		rating_privacy = (ImageView) getActivity().findViewById(
				R.id.rating_privacy);

		share_on_facebook = (CheckBox) getActivity().findViewById(
				R.id.share_on_facebook);

		listEditText = new ArrayList<EditText>();

		LayoutInflater inflater = LayoutInflater.from(getActivity());

		privacy = Integer.parseInt(ContentManager.getInstance()
				.getCurrentUser().getUser_setting());

		contentAddPhoto = inflater.inflate(R.layout.popup_upload_picture, null);
		contentAddComment = inflater.inflate(R.layout.popup_add_comment, null);
		contentPrivacy = inflater.inflate(R.layout.popup_privacy_for_rating,
				null);

		initCategoryData();
	}

	private void execute() {
		share_on_facebook.setChecked(true);

		content_category_expand_button.setOnClickListener(expandCategoryClick);
		content_criteria_expand_button.setOnClickListener(expandCriteriaClick);

		title.setText(getResources().getString(R.string.rating_page));
		rating_submit_rating.setOnClickListener(submitClick);

		rating_add_photo.setOnClickListener(add_photo);
		rating_add_comment.setOnClickListener(add_comment);
		rating_privacy.setOnClickListener(add_privacy);
	}

	OnClickListener add_photo = new OnClickListener() {

		@Override
		public void onClick(View v) {
			pw_photo = new PopupWindow(contentAddPhoto,
					LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, true);

			Button choose_file_upload = (Button) contentAddPhoto
					.findViewById(R.id.choose_file_upload);

			Button canceluploadphoto = (Button) contentAddPhoto
					.findViewById(R.id.canceluploadphoto);

			upload_file_name = (TextView) contentAddPhoto
					.findViewById(R.id.upload_file_name);

			choose_file_upload.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					showChooser();
				}
			});

			canceluploadphoto.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {

					pw_photo.dismiss();
				}
			});

			pw_photo.setBackgroundDrawable(new BitmapDrawable());
			pw_photo.setAnimationStyle(android.R.style.Animation_Dialog);
			pw_photo.showAtLocation(mainView, Gravity.CENTER, 0, 15);
			pw_photo.setOnDismissListener(new OnDismissListener() {

				@Override
				public void onDismiss() {
				}
			});

		}
	};

	private void showChooser() {
		// Use the GET_CONTENT intent from the utility class
		Intent target = FileUtils.createGetContentIntent();
		// Create the chooser Intent
		Intent intent = Intent.createChooser(target,
				getString(R.string.chooser_title));
		try {
			startActivityForResult(intent, REQUEST_CODE);
		} catch (ActivityNotFoundException e) {
			// The reason for the existence of aFileChooser
		}
	}

	OnClickListener add_comment = new OnClickListener() {

		@Override
		public void onClick(View v) {
			final PopupWindow pw = new PopupWindow(contentAddComment,
					LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, true);

			final EditText edt = (EditText) contentAddComment
					.findViewById(R.id.content_comment);
			Button addComment = (Button) contentAddComment
					.findViewById(R.id.addComment);
			Button cancelComment = (Button) contentAddComment
					.findViewById(R.id.cancelComment);

			edt.setFocusable(true);
			InputMethodManager imm = (InputMethodManager) getActivity()
					.getSystemService(Context.INPUT_METHOD_SERVICE);
			imm.showSoftInput(edt, InputMethodManager.SHOW_IMPLICIT);

			cancelComment.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					InputMethodManager imm = (InputMethodManager) getActivity()
							.getSystemService(Context.INPUT_METHOD_SERVICE);
					imm.hideSoftInputFromWindow(edt.getWindowToken(), 0);

					edt.setText("");
					pw.dismiss();
				}
			});

			addComment.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					if (!edt.getText().toString().trim().equals("")) {

						ContentManager.getInstance().setCommentContent(
								edt.getText().toString());
						InputMethodManager imm = (InputMethodManager) getActivity()
								.getSystemService(Context.INPUT_METHOD_SERVICE);
						imm.hideSoftInputFromWindow(edt.getWindowToken(), 0);
						pw.dismiss();

					} else {
						Toast.makeText(
								v.getContext(),
								getResources().getString(
										R.string.comment_nothing),
								Toast.LENGTH_SHORT).show();
					}

				}
			});

			pw.setBackgroundDrawable(new BitmapDrawable());
			pw.setAnimationStyle(android.R.style.Animation_Dialog);
			pw.showAtLocation(mainView, Gravity.CENTER, 0, 15);
			pw.setOnDismissListener(new OnDismissListener() {

				@Override
				public void onDismiss() {
				}
			});

		}
	};

	OnClickListener add_privacy = new OnClickListener() {

		@Override
		public void onClick(View v) {
			final PopupWindow pw = new PopupWindow(contentPrivacy,
					LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, true);

			pw.setBackgroundDrawable(new BitmapDrawable());
			pw.setAnimationStyle(android.R.style.Animation_Dialog);
			pw.showAtLocation(mainView, Gravity.CENTER, 0, 15);

			final TextView tv_open_public = (TextView) contentPrivacy
					.findViewById(R.id.open_to_public);
			final TextView tv_only_friend = (TextView) contentPrivacy
					.findViewById(R.id.only_friend);
			final TextView tv_anonymise = (TextView) contentPrivacy
					.findViewById(R.id.anonymise);

			Button ok_but = (Button) contentPrivacy
					.findViewById(R.id.addPrivacyOK);
			ok_but.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					pw.dismiss();
					privacy = temp;
				}
			});

			switch (privacy) {
			case 1:
				tv_open_public.setBackgroundColor(Color.rgb(139, 137, 130));
				tv_open_public.setTextColor(Color.WHITE);

				tv_only_friend
						.setBackgroundResource(R.drawable.category_item_background);
				tv_only_friend.setTextColor(Color.BLACK);

				tv_anonymise
						.setBackgroundResource(R.drawable.category_item_background);
				tv_anonymise.setTextColor(Color.BLACK);

				break;
			case 2:
				tv_open_public
						.setBackgroundResource(R.drawable.category_item_background);
				tv_open_public.setTextColor(Color.BLACK);

				tv_only_friend.setBackgroundColor(Color.rgb(139, 137, 130));
				tv_only_friend.setTextColor(Color.WHITE);

				tv_anonymise
						.setBackgroundResource(R.drawable.category_item_background);
				tv_anonymise.setTextColor(Color.BLACK);

				break;
			case 3:
				tv_open_public
						.setBackgroundResource(R.drawable.category_item_background);
				tv_open_public.setTextColor(Color.BLACK);
				tv_only_friend
						.setBackgroundResource(R.drawable.category_item_background);
				tv_only_friend.setTextColor(Color.BLACK);

				tv_anonymise.setBackgroundColor(Color.rgb(139, 137, 130));
				tv_anonymise.setTextColor(Color.WHITE);
				break;

			default:
				break;
			}

			tv_open_public.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {

					ContentManager.getInstance().setRating_privacy(0);

					tv_open_public.setBackgroundColor(Color.rgb(139, 137, 130));
					tv_open_public.setTextColor(Color.WHITE);

					tv_only_friend
							.setBackgroundResource(R.drawable.category_item_background);
					tv_only_friend.setTextColor(Color.BLACK);
					tv_anonymise
							.setBackgroundResource(R.drawable.category_item_background);
					tv_anonymise.setTextColor(Color.BLACK);
					temp = 1;
				}
			});

			tv_only_friend.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {

					ContentManager.getInstance().setRating_privacy(1);

					tv_open_public
							.setBackgroundResource(R.drawable.category_item_background);
					tv_open_public.setTextColor(Color.BLACK);

					tv_only_friend.setBackgroundColor(Color.rgb(139, 137, 130));
					tv_only_friend.setTextColor(Color.WHITE);

					tv_anonymise
							.setBackgroundResource(R.drawable.category_item_background);
					tv_anonymise.setTextColor(Color.BLACK);
					temp = 2;
				}
			});

			tv_anonymise.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {

					ContentManager.getInstance().setRating_privacy(2);

					tv_open_public
							.setBackgroundResource(R.drawable.category_item_background);
					tv_open_public.setTextColor(Color.BLACK);
					tv_only_friend
							.setBackgroundResource(R.drawable.category_item_background);
					tv_only_friend.setTextColor(Color.BLACK);

					tv_anonymise.setBackgroundColor(Color.rgb(139, 137, 130));
					tv_anonymise.setTextColor(Color.WHITE);
					temp = 3;
				}
			});

			pw.setOnDismissListener(new OnDismissListener() {

				@Override
				public void onDismiss() {
				}
			});
		}
	};

	private void initCategoryView(int x) {
		String str = ContentManager.getInstance().getRating_category()
				.getCategory_name();
		content_category_rank.setText(str);
		ratingCategoryDetailContent.removeAllViews();
		List<RatingDetailType> ldc = ContentManager.getInstance()
				.getListRatingCategory().get(x).getListDetails();
		listEditText.clear();
		for (int i = 0; i < ldc.size(); i++)
			addViewDetail(ldc.get(i));

	}

	private void addViewDetail(RatingDetailType ratingDetail) {
		TextView tv = new TextView(getActivity());
		EditText et = new EditText(getActivity());

		float density = getResources().getDisplayMetrics().density;

		tv.setPadding((int) (10 * density), (int) (15 * density), 0,
				(int) (5 * density));
		tv.setTextAppearance(getActivity(),
				android.R.style.TextAppearance_Medium);
		tv.setTextColor(Color.rgb(69, 69, 69));

		et.setInputType(InputType.TYPE_CLASS_TEXT);

		et.setTextAppearance(getActivity(),
				android.R.style.TextAppearance_Medium);
		et.setBackgroundColor(0x66bbbbbb);

		int screenLayout = getActivity().getResources().getConfiguration().screenLayout;
		screenLayout &= Configuration.SCREENLAYOUT_SIZE_MASK;
		switch (screenLayout) {
		case Configuration.SCREENLAYOUT_SIZE_SMALL:
			et.setPadding((int) (5 * density), (int) (5 * density),
					(int) (5 * density), (int) (5 * density));

			break;
		case Configuration.SCREENLAYOUT_SIZE_NORMAL:
			et.setPadding((int) (10 * density), (int) (10 * density),
					(int) (10 * density), (int) (10 * density));
			break;
		case Configuration.SCREENLAYOUT_SIZE_LARGE:
			et.setPadding((int) (10 * density), (int) (10 * density),
					(int) (10 * density), (int) (10 * density));
			break;
		case 4: // Configuration.SCREENLAYOUT_SIZE_XLARGE is API >= 9
			et.setPadding((int) (10 * density), (int) (10 * density),
					(int) (10 * density), (int) (10 * density));
			break;
		default:
			et.setPadding((int) (5 * density), (int) (5 * density),
					(int) (5 * density), (int) (5 * density));
			break;
		}

		tv.setText(ratingDetail.getTitle());
		et.setHint(ratingDetail.getHint());

		ratingCategoryDetailContent.addView(tv);
		ratingCategoryDetailContent.addView(et);

		listEditText.add(et);
	}

	private void initCategoryData() {

		dialog = ProgressDialog.show(getActivity(),
				getResources().getString(R.string.load_category),
				getResources().getString(R.string.loading), true);

		ratingCategoryDao.getListCategory(handlerGetCategory, getActivity(),
				dialog);

	}

	OnClickListener submitClick = new OnClickListener() {

		@Override
		public void onClick(View v) {

			int checkValue = checkSubmitCondition();
			if (checkValue == 0) {

				dialog = ProgressDialog.show(getActivity(), getResources()
						.getString(R.string.submit_rating), getResources()
						.getString(R.string.loading), true);

				ratingCategoryDao.submitRating(handlerSubmitRating,
						getActivity(),
						listEditText.get(0).getText().toString(), listEditText
								.get(1).getText().toString(), privacy + "",
						share_on_facebook.isChecked() ? "0" : "1", dialog);
			} else {
				switch (checkValue) {
				case 1:
					Toast.makeText(getActivity(),
							getString(R.string.connection_error),
							Toast.LENGTH_SHORT).show();

					break;
				case 2:
					Toast.makeText(getActivity(),
							getString(R.string.sub_field_null),
							Toast.LENGTH_SHORT).show();
					break;
				case 3:
					Toast.makeText(getActivity(),
							getString(R.string.comment_null),
							Toast.LENGTH_SHORT).show();
					break;

				case 4:
					Toast.makeText(getActivity(),
							getString(R.string.criteria_null),
							Toast.LENGTH_SHORT).show();
					break;

				default:
					break;
				}
			}
		}
	};

	private int checkSubmitCondition() {

		if (listEditText.size() < 2)
			return 1;

		if (listEditText.get(0).getText().toString().equals("")
				|| listEditText.get(1).getText().toString().equals(""))
			return 2;

		if (ContentManager.getInstance().getCommentContent().equals(""))
			return 3;

		if (!ratingCategoryDao.checkCriteria())
			return 4;

		return 0;
	}

	OnClickListener expandCriteriaClick = new OnClickListener() {

		@Override
		public void onClick(View v) {

			Intent intent = new Intent(getActivity(),
					ListCriteriaActivity.class);
			startActivity(intent);
		}
	};

	OnClickListener expandCategoryClick = new OnClickListener() {

		@Override
		public void onClick(View v) {

			Intent intent = new Intent(getActivity(),
					ListCategoryActivity.class);
			startActivity(intent);
			// getActivity().overridePendingTransition(0,R.drawable.fateout);
		}
	};

	AsyncHttpResponseHandler handlerGetCategory = new AsyncHttpResponseHandler() {
		@Override
		public void onSuccess(int statusCode, Header[] headers, byte[] response) {

			System.out.println("Success register");

			List<RatingCategory> lrc = new ArrayList<RatingCategory>();

			lrc = ratingCategoryDao.parseListData(new String(response));

			ContentManager.getInstance().setListRatingCategory(lrc);

			if (ContentManager.getInstance().getRating_category() == null)
				ContentManager.getInstance().setRating_category(
						lrc.size() > 0 ? lrc.get(0) : null);

			if (ContentManager.getInstance().getListRatingCategory().size() > 0) {
				if (ContentManager.getInstance().getCategory_index_selected() == 0) {
					initCategoryView(0);
				}
			}
		}

		@Override
		public void onStart() {
			System.out.println("Start");
		}

		@Override
		public void onFinish() {
			if (dialog != null)
				dialog.dismiss();
		}

		@Override
		public void onFailure(int statusCode, Header[] headers,
				byte[] errorResponse, Throwable e) {
			System.out.println("Fail Register");
			try {
				JSONObject obj = new JSONObject(new String(errorResponse));

				Toast.makeText(getActivity(),
						obj.getString("message").toString(), Toast.LENGTH_SHORT)
						.show();
			} catch (Exception ex) {

			}
		}
	};

	private String getBitmap(String tag, Uri url) {
		File cacheDir;
		// if the device has an SD card
		if (android.os.Environment.getExternalStorageState().equals(
				android.os.Environment.MEDIA_MOUNTED)) {
			cacheDir = new File(
					android.os.Environment.getExternalStorageDirectory(),
					".OCFL311");
		} else {
			// it does not have an SD card
			cacheDir = getActivity().getCacheDir();
		}
		if (!cacheDir.exists())
			cacheDir.mkdirs();

		File f = new File(cacheDir, tag);
		try {
			if (f.exists()) {
				f.delete();
				f.createNewFile();
			} else {
				f.createNewFile();
			}

		} catch (Exception e) {

		}
		try {
			InputStream is = null;
			if (url.toString().startsWith(
					"content://com.google.android.gallery3d")) {
				is = getActivity().getContentResolver().openInputStream(url);
			} else {
				is = new URL(url.toString()).openStream();
			}
			OutputStream os = new FileOutputStream(f);

			byte[] buffer = new byte[1024];
			int len;
			while ((len = is.read(buffer)) != -1) {
				os.write(buffer, 0, len);
			}

			os.close();
			return f.getAbsolutePath();
		} catch (Exception ex) {
			// something went wrong
			ex.printStackTrace();
			return null;
		}
	}

	AsyncHttpResponseHandler handlerSubmitRating = new AsyncHttpResponseHandler() {
		@Override
		public void onSuccess(int statusCode, Header[] headers, byte[] response) {

			System.out.println("Success register");
			try {
				JSONObject obj = new JSONObject(new String(response));

				Toast.makeText(getActivity(),
						obj.getString("message").toString(), Toast.LENGTH_SHORT)
						.show();
			} catch (Exception ex) {

			}
		}

		@Override
		public void onStart() {
			System.out.println("Start");
		}

		@Override
		public void onFinish() {
			if (dialog != null)
				dialog.dismiss();
		}

		@Override
		public void onFailure(int statusCode, Header[] headers,
				byte[] errorResponse, Throwable e) {
			System.out.println("Fail Register");
			try {
				JSONObject obj = new JSONObject(new String(errorResponse));

				Toast.makeText(getActivity(),
						obj.getString("message").toString(), Toast.LENGTH_SHORT)
						.show();
			} catch (Exception ex) {

			}
		}
	};

}
